<template>
    <div class ='search'>
      <!-- 导航栏 -->
      <van-nav-bar title="商品搜索" left-arrow @click-left="$router.go(-1)"/>
      <!-- 搜索框 -->
      <van-search v-model="searchItem" show-action placeholder="请输入搜索关键词" clearable shape="round">
        <template #action>
          <div @click="goSearch(searchItem)" >搜索</div>
        </template>
      </van-search>
      <!-- 搜索历史 -->
      <div class="search-history" v-if="historyList.length > 0">
        <div class="title">
          <span>最近搜索</span>
          <van-icon @click="clear" name="delete-o" size="16" />
        </div>
        <div class="list" >
          <div class="list-item" v-for="item in historyList" :key="item" @click="goSearch(item)">
            {{ item }}
          </div>
        </div>
      </div>
  </div>
</template>

<script>
import { getHistoryList, setHistoryList } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  data () {
    return {
      searchItem: '',
      historyList: getHistoryList()
    }
  },
  methods: {
    goSearch (item) {
      const index = this.historyList.indexOf(item)
      // 若搜索框为空则不进行搜索
      if (!item) return
      // 若关键词存在则先删除
      if (index !== -1) {
        this.historyList.splice(index, 1)
        console.log('存在关键词,已移除' + this.historyList)
      }
      console.log(item, this.historyList)
      // 若关键词不存在则直接追加到最前面
      this.historyList.unshift(item)
      setHistoryList(this.historyList)
      this.$router.push(`/searchlist?search=${item}`)
    },
    clear () {
      this.historyList = []
      setHistoryList(this.historyList)
      this.$toast.success('清空历史成功')
    }
  }
}
</script>

<style lang="less" scoped>
.search {
  .searchBtn {
    background-color: #dd6b42;
    color: #fff;
  }
  ::v-deep .van-search__action {
    background-color: #dd6b42;
    color: #fff;
    padding: 0 20px;
    border-radius: 0 5px 5px 0;
    margin-right: 10px;
  }
  .title {
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 15px;
  }
  .list {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    padding: 0 10px;
    gap: 5%;
  }
  .list-item {
    width: 30%;
    text-align: center;
    padding: 7px;
    line-height: 15px;
    border-radius: 50px;
    background: #fff;
    font-size: 13px;
    border: 1px solid #efefef;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-bottom: 10px;
  }
}
</style>
